<template>
  <div class="delivery-task">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="任务编号">
          <el-input v-model="searchForm.taskNo" placeholder="请输入任务编号" clearable />
        </el-form-item>
        <el-form-item label="配送状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配送日期">
          <el-date-picker
            v-model="searchForm.date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>送货任务列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新建任务
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="taskNo" label="任务编号" width="180" />
        <el-table-column prop="orderCount" label="订单数量" width="100" align="center" />
        <el-table-column prop="driverName" label="配送司机" width="120" />
        <el-table-column prop="vehicleNo" label="车牌号" width="120" />
        <el-table-column prop="deliveryDate" label="配送日期" width="120" />
        <el-table-column prop="status" label="配送状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="配送区域" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="primary" 
              @click="handleStart(row)"
            >
              开始配送
            </el-button>
            <el-button 
              v-if="row.status === 'delivering'" 
              link 
              type="success" 
              @click="handleComplete(row)"
            >
              完成配送
            </el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="danger" 
              @click="handleCancel(row)"
            >
              取消任务
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 任务详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="`任务详情 - ${currentTask.taskNo}`"
      size="60%"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务编号">{{ currentTask.taskNo }}</el-descriptions-item>
        <el-descriptions-item label="配送日期">{{ currentTask.deliveryDate }}</el-descriptions-item>
        <el-descriptions-item label="配送司机">{{ currentTask.driverName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentTask.driverPhone }}</el-descriptions-item>
        <el-descriptions-item label="车牌号">{{ currentTask.vehicleNo }}</el-descriptions-item>
        <el-descriptions-item label="配送状态">
          <el-tag :type="getStatusType(currentTask.status)">
            {{ getStatusText(currentTask.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider>配送订单</el-divider>
      
      <el-table :data="currentTask.orders" border>
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="customerName" label="客户名称" width="120" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="address" label="配送地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="配送状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusType(row.status)">
              {{ getOrderStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <template v-if="currentTask.status === 'completed'">
        <el-divider>配送轨迹</el-divider>
        <el-timeline>
          <el-timeline-item
            v-for="(record, index) in currentTask.records"
            :key="index"
            :timestamp="record.time"
            :type="record.type"
          >
            {{ record.content }}
          </el-timeline-item>
        </el-timeline>
      </template>
    </el-drawer>

    <!-- 新建任务弹窗 -->
    <el-dialog
      title="新建配送任务"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="配送日期" prop="deliveryDate">
          <el-date-picker
            v-model="formData.deliveryDate"
            type="date"
            placeholder="选择配送日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="配送司机" prop="driverId">
          <el-select v-model="formData.driverId" placeholder="请选择司机">
            <el-option
              v-for="item in driverOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配送订单" prop="orderIds">
          <el-select
            v-model="formData.orderIds"
            multiple
            placeholder="请选择待配送订单"
          >
            <el-option
              v-for="item in orderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  taskNo: '',
  status: '',
  date: ''
})

// 表格相关
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 抽屉相关
const drawerVisible = ref(false)
const currentTask = ref<any>({})

// 弹窗相关
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()

const formData = ref({
  deliveryDate: '',
  driverId: '',
  orderIds: [],
  remark: ''
})

const formRules = {
  deliveryDate: [{ required: true, message: '请选择配送日期', trigger: 'change' }],
  driverId: [{ required: true, message: '请选择配送司机', trigger: 'change' }],
  orderIds: [{ required: true, message: '请选择配送订单', trigger: 'change' }]
}

// 选项数据
const statusOptions = [
  { value: 'pending', label: '待配送' },
  { value: 'delivering', label: '配送中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' }
]

const driverOptions = [
  { value: '1', label: '张三 (京A12345)' },
  { value: '2', label: '李四 (京B12345)' },
  { value: '3', label: '王五 (京C12345)' }
]

const orderOptions = [
  { value: '1', label: 'DD20231128001 - 北京市朝阳区xxx' },
  { value: '2', label: 'DD20231128002 - 北京市海淀区xxx' },
  { value: '3', label: 'DD20231128003 - 北京市西城区xxx' }
]

// 模拟数据
const tableData = ref([
  {
    taskNo: 'PS20231128001',
    orderCount: 3,
    driverName: '张三',
    driverPhone: '13800138000',
    vehicleNo: '京A12345',
    deliveryDate: '2023-11-28',
    status: 'delivering',
    address: '北京市朝阳区、海淀区',
    orders: [
      {
        orderNo: 'DD20231128001',
        customerName: '李先生',
        phone: '13900139000',
        address: '北京市朝阳区xxx街道',
        status: 'delivering'
      }
    ],
    records: [
      {
        time: '2023-11-28 09:00:00',
        content: '开始配送',
        type: 'primary'
      },
      {
        time: '2023-11-28 10:00:00',
        content: '完成第一单配送',
        type: 'success'
      }
    ]
  }
])

// 方法
const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    delivering: 'primary',
    completed: 'success',
    cancelled: 'info'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待配送',
    delivering: '配送中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || '未知状态'
}

const getOrderStatusType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    delivering: 'primary',
    completed: 'success'
  }
  return map[status] || 'info'
}

const getOrderStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待配送',
    delivering: '配送中',
    completed: '已送达'
  }
  return map[status] || '未知状态'
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const resetSearch = () => {
  searchForm.value = {
    taskNo: '',
    status: '',
    date: ''
  }
  handleSearch()
}

const loadData = async () => {
  loading.value = true
  try {
    // 这里调用接口获取数据
    total.value = tableData.value.length
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
}

const handleDetail = (row: any) => {
  currentTask.value = row
  drawerVisible.value = true
}

const handleAdd = () => {
  dialogVisible.value = true
}

const handleStart = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认开始配送该任务？')
    ElMessage.success('已开始配送')
    loadData()
  } catch {}
}

const handleComplete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认完成该配送任务？')
    ElMessage.success('配送任务已完成')
    loadData()
  } catch {}
}

const handleCancel = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认取消该配送任务？', '提示', {
      type: 'warning'
    })
    ElMessage.success('配送任务已取消')
    loadData()
  } catch {}
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        ElMessage.success('创建成功')
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('创建失败：', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 初始化
loadData()
</script>

<style scoped lang="scss">
.delivery-task {
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .el-form-item {
        margin-bottom: 0;
        margin-right: 0;
      }
    }
  }
  
  .list-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

// 响应式处理
@media screen and (max-width: 768px) {
  .delivery-task {
    .search-form {
      .el-form-item {
        width: 100%;
      }
    }
  }
}
</style> 